package org.ooho.util;

import java.sql.*;
import java.util.Map;

/**
 * Created by HugHo on 2016/9/20.
 */
public class DBManager {
    private Connection conn = null;

    public DBManager(String dbName){
        try {

            Class.forName("com.mysql.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/" + dbName;
            String username = "root";
            String password = "root";
            this.conn = DriverManager.getConnection(url, username, password);

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean isExist(String tableName, String key, String value) {
        StringBuilder sql = new StringBuilder("SELECT count(*) AS num FROM " + tableName + " WHERE " + key + " = ?");
        int rsltCount = -1;

        try(PreparedStatement pstmt = this.conn.prepareStatement(sql.toString())) {
            // create prepareStatement
            pstmt.setString(1, value);

            // execute query
            try(ResultSet rs = pstmt.executeQuery()){
                rs.next();
                rsltCount = rs.getInt("num");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return rsltCount == 1;
    }

    public final Connection getConn(){
        return this.conn;
    }

    public void close(){
        try{
            this.conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
